<script>
import {admin_get_q, admin_update_qa, delete_qa} from "@/middleware/interface";
import {ArrowRight, CopyDocument, Delete, Edit, FullScreen, Share} from "@element-plus/icons-vue";
import {ElMessage, ElMessageBox} from "element-plus";
import {QUESTION_PREFIX, SHARE_PREFIX} from "@/config";
import QrcodeVue from 'qrcode.vue'
import html2canvas from "html2canvas";

export default {
  components: {Delete, ArrowRight, FullScreen, CopyDocument, Share, Edit, QrcodeVue},
  data() {
    return {
      showPwd: false,
      lists: [],
      total: 0,
      limit: 20,
      current: 1,

      showQr: false,
      showEditName: false,//修改名字
      editNameValue: "",//修改的名字
      editNameItem: "",//修改的问卷

      qrCodeUrl: "",
      loading: true,

    };
  },
  mounted() {
    this.getData()
  },
  methods: {
    async deleteQa(qid) {
      ElMessageBox.confirm(
          '是否删除此问卷，该操作不可逆？',
          '请确认',
          {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning',
          }
      )
          .then(async () => {
            await delete_qa({
              qid: qid
            })
            ElMessage.info("删除成功！")
            await this.getData()
          })
          .catch(() => {
          })
    },
    copyUrl(qid) {
      this.$copyText(QUESTION_PREFIX + qid).then(
          res => {
            ElMessage.success("复制链接成功！")
          },
          err => {
          }
      )
    },
    async getData() {
      const res = await admin_get_q({
        offset: (this.current - 1) * this.limit,
        limit: this.limit,
      })
      this.lists = res["data"]["lists"]
      this.total = res["data"]["total"]
      console.log(res)
      this.loading = false
    },
    getShort(date) {
      const dateObj = new Date(date);
      const year = dateObj.getFullYear();
      const month = dateObj.getMonth() + 1; // 月份从0开始，所以需要加1
      const day = dateObj.getDate();
      const hours = dateObj.getHours();
      const minutes = dateObj.getMinutes();
      const seconds = dateObj.getSeconds();
      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
    },
    getMonthDay(date) {
      const dateObj = new Date(date);
      const month = dateObj.getMonth() + 1; // 月份从0开始，所以需要加1
      const day = dateObj.getDate();
      return `${month}-${day}`
    },
    getQaName(res) {
      if (JSON.parse(res.content).name) {
        return JSON.parse(res.content).name
      } else {
        return "会议收集" + this.getMonthDay(res.create_time)
      }
    },
    async updateQa(item) {
      await admin_update_qa({
        "qid": item.question_id,
        "content": item.content,
        "is_activate": item.is_activate,
      })
      ElMessage.success("更新投票状态成功！")
      await this.getData()
    },
    lookData(qid) {
      this.$router.push({
        path: "list",
        query: {
          "qid": qid
        }
      })
    },
    async confirmChangeName() {
      const tmp = JSON.parse(this.editNameItem.content)
      tmp.name = this.editNameValue
      //确认更改问卷名字
      await admin_update_qa({
        qid: this.editNameItem.question_id,
        content: JSON.stringify(tmp),
        is_activate: this.editNameItem.is_activate,
      })
      this.showEditName = false
      ElMessage.success("更改成功！")
      await this.getData()
    },
    changeName(res) {
      //更改问卷名字
      this.showEditName = true
      this.editNameValue = JSON.parse(res.content).name || ""
      this.editNameItem = res
    },
    showQrCode(qid) {
      this.showQr = true
      this.qrCodeUrl = QUESTION_PREFIX + qid
    },
    shareData(qid) {
      this.$copyText(SHARE_PREFIX + "?qid=" + qid + "&tk=" + localStorage.token).then(
          res => {
            ElMessage.success("复制分享链接成功！")
          },
          err => {
          }
      )
    },
    downLoadQr() {
      const qrcodeElement = document.getElementById('qrcode-container');
      html2canvas(qrcodeElement).then((canvas) => {
        // 把生成的base64位图片上传到服务器,生成在线图片地址
        let url = canvas.toDataURL('image/png') // toDataURL: 图片格式转成 base64
        this.imgUrl = url
        //将图片下载到本地
        let a = document.createElement('a') // 生成一个a元素
        let event = new MouseEvent('click') // 创建一个单击事件
        a.download = '图片名' // 设置图片名称没有设置则为默认
        a.href = this.imgUrl // 将生成的URL设置为a.href属性
        a.dispatchEvent(event) // 触发a的单击事件
      });
    }
  },
};
</script>

<template>

  <el-dialog v-model="showQr" style="border-radius: 20px; min-width: 320px">
    <div class="flex flex-col items-center justify-center">
      <div id="qrcode-container" class="mix-blend-darken">
        <qrcode-vue render-as="svg" class="" size="150" :value="qrCodeUrl"
                    level="H"/>
      </div>
      <div @click="downLoadQr()"
           class=" cursor-pointer select-none hover:opacity-50 px-5 py-2 mt-5 bg-gray-100 border border-gray-200 text-gray-800 font-bold rounded-xl">
        下载二维码
      </div>
    </div>
  </el-dialog>


  <el-dialog v-model="showEditName" style="border-radius: 20px; min-width: 320px">
    <div class="flex flex-col items-center justify-center">
      <textarea placeholder="点我填写问卷名称" class="px-4 py-4 rounded-xl bg-gray-100 h-32" type="text"
                v-model="editNameValue"/>
      <div @click="confirmChangeName()"
           class=" cursor-pointer select-none hover:opacity-50 px-5 py-2 mt-5 bg-gray-100 border border-gray-200 text-gray-800 font-bold rounded-xl">
        更改名字
      </div>
    </div>
  </el-dialog>

  <el-empty v-if="lists.length===0" :description="loading?'加载中…':'暂无问卷数据'"/>

  <div v-for="item in lists" class=" max-w-5xl mx-auto">
    <div class="bg-white px-5 py-3 sm:py-5 sm:pb-6 pb-4 mx-2 my-4 rounded-2xl flex flex-col items-start">
      <div class="flex items-center justify-between w-full">
        <div class="flex items-center">
          <div class="font-bold" style="font-size: 16px">{{ getQaName(item) }}</div>
          <div @click="changeName(item)" class="ml-2 hover:opacity-50 cursor-pointer"
               style="line-height: 10px">
            <el-icon>
              <Edit/>
            </el-icon>
          </div>
        </div>

        <div class="flex items-center">
          <!--          <div style="color: #2c2c2c" class="hidden sm:flex items-center cursor-pointer select-none hover:opacity-50">-->
          <!--            <div @click="shareData(item.question_id)" style="line-height: 10px" class="mr-1">-->
          <!--              <el-icon>-->
          <!--                <Share/>-->
          <!--              </el-icon>-->
          <!--            </div>-->
          <!--            <div></div>-->
          <!--          </div>-->

          <div style="color: #000" @click="deleteQa(item.question_id)" v-if="item.is_activate"
               class="hidden sm:flex items-center ml-5 cursor-pointer select-none hover:opacity-50">
            <div style="line-height: 10px" class="mr-1">
              <el-icon>
                <Delete/>
              </el-icon>
            </div>
            <div></div>
          </div>

          <div style="color: #000" @click="copyUrl(item.question_id)" v-if="item.is_activate"
               class="hidden sm:flex items-center ml-5 cursor-pointer select-none hover:opacity-50">
            <div style="line-height: 10px" class="mr-1">
              <el-icon>
                <CopyDocument/>
              </el-icon>
            </div>
            <div></div>
          </div>

          <div style="color: #000" @click="showQrCode(item.question_id)" v-if="item.is_activate"
               class="hidden sm:flex items-center ml-5 cursor-pointer select-none hover:opacity-50">
            <div style="line-height: 10px" class="mr-1">
              <img src="../assets/img/qrcode.svg" class="w-5 h-5">
            </div>
            <div></div>
          </div>

          <div class=" ml-5 mr-2">
            <div class="w-16 text-right" :style="{
              color: item.is_activate?'#0a1ade':'#6e6e6e'
            }">{{ item.is_activate ? '收集中…' : '已停止收集' }}
            </div>
          </div>

          <el-switch @click="updateQa(item)" v-model="item.is_activate" active-color="#0a1ade"/>
        </div>

      </div>
      <div class="flex justify-between w-full items-center mt-2 text-gray-500">
        <div class="flex items-center">
          <div class="sm:block hidden">已收集 {{ item.count }} 份</div>
          <div class="sm:hidden block">创建于 {{ getShort(item.update_time) }}</div>
          <div class="ml-5 sm:block hidden">创建于 {{ getShort(item.update_time) }}</div>
        </div>
        <div @click="lookData(item.question_id)"
             class="cursor-pointer sm:flex items-center hidden select-none hover:text-blue-700">查看数据
          <el-icon class="ml-1">
            <ArrowRight></ArrowRight>
          </el-icon>
        </div>
        <div @click="lookData(item.question_id)"
             class="cursor-pointer sm:hidden flex items-center select-none hover:text-blue-700">已收集 {{ item.count }}
          份
          <el-icon class="ml-1">
            <ArrowRight></ArrowRight>
          </el-icon>
        </div>
      </div>
      <div class="w-full mt-4 mb-1 sm:hidden" v-if="item.is_activate" style="height: 1px; background: #EEEEEE;">
        <!--        <div class="bg-gray-100 mt-2.5 px-2.5 py-1 w-full rounded text-gray-600 text-sm sm:hidden block">创建于-->
        <!--          {{ getShort(item.update_time) }}-->
        <!--        </div>-->
      </div>


      <div v-if="item.is_activate" class="flex items-center w-full justify-between h-12 sm:h-0">

        <div style="color: #2c2c2c"
             class="flex sm:hidden items-center cursor-pointer select-none px-1 py-2">
          <!--          <div @click="shareData(item.question_id)" style="line-height: 10px" class="mr-1 hover:opacity-50">-->
          <!--            <el-icon>-->
          <!--              <Share/>-->
          <!--            </el-icon>-->
          <!--          </div>-->

          <div @click="showQrCode(item.question_id)" style="line-height: 10px"
               class=" hover:opacity-50 flex items-center">
            <img src="../assets/img/qrcode.svg" class="w-5 h-5">
            <div class="ml-1">下载二维码</div>
          </div>
          <div style="color: #000" @click="deleteQa(item.question_id)" v-if="item.is_activate"
               class="flex items-center ml-5 cursor-pointer select-none hover:opacity-50">
            <div style="line-height: 10px" class="mr-1">
              <el-icon>
                <Delete/>
              </el-icon>
            </div>
            <div></div>
          </div>
        </div>

        <div style="color: #0e1ad5;border-color: #0e1ad5;" @click="copyUrl(item.question_id)" v-if="item.is_activate"
             class=" mt-1.5 mb-0.5 flex sm:hidden items-center cursor-pointer select-none hover:opacity-50 px-3.5 py-1.5 ml-3 border-2 rounded-full">
          <div class="font-bold" style="font-size: 13.5px;">复制问卷链接</div>
        </div>
      </div>

      <!--      {{ item }}-->
    </div>
  </div>

  <div v-if="total>limit" class=" flex justify-center items-center mb-20 mt-10">
    <div class=" px-5 py-2 bg-white rounded-xl">
      <el-pagination layout="prev, pager, next" :hide-on-single-page="true" v-model:current-page="current"
                     v-model:page-size="limit" :total="total"
                     @current-change="getData()"/>
    </div>
  </div>

</template>

<style scoped>
</style>